package com.estudy.service;

import com.estudy.bean.KnowledgeDO;
import com.estudy.bean.KnowledgeDOExample;
import com.estudy.dao.KnowledgeDOMapper;
import com.estudy.entity.KnowLedgeEnum;
import com.estudy.entity.Knowledge;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author: yi.jianhua
 * @create: 2019/09/04 17:46
 */
@Service
public class FileService {
    private static final Logger logger = Logger.getLogger(UserService.class);
    @Autowired
    private KnowledgeDOMapper mapper;

    public void saveKnowledge(Knowledge knowledge) {
        KnowledgeDO kn = convert2DO(knowledge);
        mapper.insertSelective(kn);
    }

    private KnowledgeDO convert2DO(Knowledge knowledge) {
        KnowledgeDO result = new KnowledgeDO();
        result.setApproval(knowledge.getApproval());
        result.setContent(knowledge.getKnowledgeDesc());
        result.setFile_path(knowledge.getFilePath());
        result.setId(knowledge.getFid());
        result.setKlcatid(knowledge.getKnowledge());
        result.setTitle(knowledge.getTitle());
        result.setUpuid(knowledge.getUid());
        return result;
    }

    public List<Knowledge> queryAllFiles() {
        KnowledgeDOExample knowledgeDOExample = new KnowledgeDOExample();
        List<KnowledgeDO> knowledgeDOS = mapper.selectByExample(knowledgeDOExample);
        return convert2KnowledgeList(knowledgeDOS);
    }

    private List<Knowledge> convert2KnowledgeList(List<KnowledgeDO> knowledgeDOS) {
        if (CollectionUtils.isEmpty(knowledgeDOS)) {
            return Collections.emptyList();
        }
        List<Knowledge> result = new ArrayList<Knowledge>(knowledgeDOS.size());
        for (KnowledgeDO DO : knowledgeDOS) {
            Knowledge knowledge = convertKnowledge(DO);
            result.add(knowledge);
        }
        return result;
    }

    private Knowledge convertKnowledge(KnowledgeDO DO) {
        Knowledge knowledge = new Knowledge();
        knowledge.setFid(DO.getId());
        knowledge.setTitle(DO.getTitle());
        knowledge.setKnowledgeDesc(DO.getContent());
        knowledge.setKnowledge(DO.getKlcatid());
        knowledge.setKnowCategy(KnowLedgeEnum.getEnumByCode(DO.getKlcatid()).getName());
        knowledge.setApproval(DO.getApproval());
        return knowledge;
    }

    public Knowledge queryFileById(String fid) {
        KnowledgeDO knowledgeDO = mapper.selectByPrimaryKey(fid);
        return convertKnowledge(knowledgeDO);
    }

    public void updateKnowledge(Knowledge knowledge) {
        KnowledgeDO knowledgeDO = convert2DO(knowledge);
        mapper.updateByPrimaryKeySelective(knowledgeDO);
    }

    public void delFileInfo(String id) {
        mapper.deleteByPrimaryKey(id);
    }
}
